//
//  GBRequest.m
//  和讯股票
//
//  Created by guobin on 14-9-27.
//  Copyright (c) 2014年 guobin. All rights reserved.
//

#import "GBRequest.h"

@interface GBRequest ()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
{
    //要请求的链接
//    NSURL *_url;
    //数据源
    NSMutableData *_rootData;
    NSURLConnection *connection;
    
}
/**  <#Description#> */


@end

@implementation GBRequest

//获取request实例的方法
- (instancetype)initWithUrlStr:(NSString *)urlStr
{
    self = [super init];
    if (self) {
        //获取传来的链接
        NSString* webStringURL = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *urlStr = [webStringURL stringByReplacingOccurrencesOfString:@"+" withString:@"%2B" options:NSLiteralSearch range:NSMakeRange(0, webStringURL.length)];
        NSURL *url = [NSURL URLWithString:urlStr];
        _url = url;
        _rootData = [NSMutableData data];

        //初始化数据源
    }
    return self;
}
//- (void)setUrl:(NSURL *)url{
//    _url  = url;
//    _rootData = [NSMutableData data];
//
//}
#pragma mark - 开始异步请求数据
- (void)startRequestData
{
    //请求数据
    NSURLRequest *request = [NSURLRequest requestWithURL:_url];
    connection = [NSURLConnection connectionWithRequest:request delegate:self];
}

#pragma mark 请求数据协议
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //清空数据源
    _rootData.length = 0;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //追加数据
    [_rootData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //先赋值
    self.requestData = _rootData;
    //NSLog(@"**");
    //如果代理响应了协议数据请求成功的方法
    self.requestStr = [[NSString alloc]initWithData:_rootData encoding:NSUTF8StringEncoding];

    if ([self.delegate respondsToSelector:@selector(requestDidFinished:)]) {
        //回调
        [self.delegate requestDidFinished:self];
    }
    //[connection cancel];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //如果代理响应了请求数据失败的方法
    if ([self.delegate respondsToSelector:@selector(requestDidFailedWithError:)]) {
//        NSLog(@"%@", error);
        //回调
        [self.delegate requestDidFailedWithError:error];
    }
    //[connection cancel];
}

@end
